import {createElementVNode, createTextVNode} from "./vdom/index";
import Watcher from "./observe/watcher";

function createEle(vnode) {
    let {tag, data, children, text} = vnode
    console.log(tag)
    if (typeof tag === 'string') { // 标签
        vnode.el = document.createElement(tag)
        patchProps(vnode.el, data)
        children.forEach(child => {
            vnode.el.appendChild(createEle(child))
        })
    }else {
        vnode.el = document.createTextNode(text)
    }
    return vnode.el
}
function patchProps(el, props) {

    for (const propsKey in props) {
        if (propsKey === 'style') {
            for (let styleName in props.style) {
                el.style[styleName] = props.style[styleName]
            }
        } else {
            el.setAttribute(propsKey, props[propsKey])
        }

    }
}
function patch(oldVNode, vnode) {

    const isRealElement = oldVNode.nodeType;
//     初始渲染
    if (isRealElement) {
        const element = oldVNode;
        const parentElement = element.parentNode;

        let newElement = createEle(vnode);
        parentElement.insertBefore(newElement, element.nextSibling)
        parentElement.removeChild(element)

    } else {

    }
}
export function initLifeCycle(Vue) {
    Vue.prototype._update = function (vnode) {
        const vm = this
        const el = vm.$el
        patch(el, vnode)
    }
    // _c('div',{attrs})
    Vue.prototype._c = function () {
        return createElementVNode(this, ...arguments)
    }
    Vue.prototype._v = function () {
        return createTextVNode(this, ...arguments)
    }
    Vue.prototype._s = function (value) {
        console.log("value",value)
        if(typeof value !== 'object') return value
        return JSON.stringify(value)
    }
    Vue.prototype._render = function () {
        return this.$options.render.call(this);
    }
}

export function mountComponent(vm, el) {
    vm.$el = el
    // 1调用render产生虚拟节点
    const updateComponent = () => {
        vm._update(vm._render())
    }
    new Watcher(vm, updateComponent,true)

}
